/*
 * @Author: Trae AI
 * @Date: 2024-05-14
 * @LastEditors: Trae AI
 * @LastEditTime: 2024-05-14
 * @Description: 脚本运行页面
 */

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hzy_normal_tool/hzy_normal_tool.dart';
import 'package:file_picker/file_picker.dart';
import 'package:provider/provider.dart';
import '../vm/script_runner_vm.dart';
import '../base_ui_config/base_ui_config_index.dart';
import '../widgets/script_runner/info_section.dart';
import '../widgets/script_runner/action_buttons.dart';
import '../widgets/script_runner/output_section.dart';

class ScriptRunnerPage extends StatefulWidget {
  const ScriptRunnerPage({super.key, this.title = "脚本运行"});
  final String title;

  @override
  State<ScriptRunnerPage> createState() => _ScriptRunnerPageState();
}

class _ScriptRunnerPageState extends BaseStateV<ScriptRunnerPage> {
  late ScriptRunnerViewModel _viewModel;

  @override
  bool get isNeedScaffol => true;

  @override
  bool get isShowAppBar => true;

  @override
  String? get appBarTitle => widget.title;

  @override
  void initState() {
    super.initState();
    // 初始化数据
    pageState = PageState.dataFetchState;

    // 初始化ViewModel
    _viewModel = ScriptRunnerViewModel();
  }

  // 选择输出目录
  Future<void> _selectOutputDirectory() async {
    try {
      String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
      if (selectedDirectory != null) {
        _viewModel.updateOutputPath(selectedDirectory);
      }
    } catch (e) {
      dPrint("选择目录出错: $e");
    }
  }

  // 选择Flutter SDK路径
  Future<void> _selectFlutterSdkPath() async {
    try {
      String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
      if (selectedDirectory != null) {
        // 检查是否选择了Flutter SDK根目录
        final binDir = Directory('$selectedDirectory/bin');
        if (await binDir.exists()) {
          final flutterExe = File('${binDir.path}/flutter');
          if (await flutterExe.exists()) {
            _viewModel.updateFlutterSdkPath(flutterExe.path);
            return;
          }
        }

        // 检查是否选择了bin目录
        final flutterExe = File('$selectedDirectory/flutter');
        if (await flutterExe.exists()) {
          _viewModel.updateFlutterSdkPath(flutterExe.path);
          return;
        }

        // 如果都不是，提示用户选择正确的目录
        setState(() {
          _viewModel.commandOutput +=
              "\n警告: 所选目录不是有效的Flutter SDK目录，请选择Flutter SDK根目录或bin目录\n";
        });
      }
    } catch (e) {
      dPrint("选择Flutter SDK目录出错: $e");
    }
  }

  // 运行脚本
  Future<void> _runScript() async {
    // 检查参数是否有效
    final String? validationError = await _viewModel.validateScriptParams();
    if (validationError != null) {
      // 显示参数错误对话框
      _showParamErrorDialog(validationError);
      return;
    }

    bool success = await _viewModel.runScript();
    if (success) {
      _showSuccessDialog();
    } else if (_viewModel.commandOutput.contains("脚本执行完成，退出码: 0")) {
      _showPartialSuccessDialog();
    }
  }

  // 停止脚本
  void _stopScript() {
    _viewModel.stopScript();
  }

  // 显示成功对话框
  void _showSuccessDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("创建成功"),
        content: Text(
            "项目已成功创建在: ${_viewModel.outputPath}/${_viewModel.projectName}"),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text("确定"),
          ),
        ],
      ),
    );
  }

  // 显示部分成功对话框
  void _showPartialSuccessDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("部分成功"),
        content: Text(
            "脚本执行成功，但未能在 ${_viewModel.outputPath}/${_viewModel.projectName} 找到项目目录。请检查命令输出获取更多信息。"),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text("确定"),
          ),
        ],
      ),
    );
  }

  // 显示参数错误对话框
  void _showParamErrorDialog(String errorMessage) {
    // 默认按钮操作
    List<Widget> actionButtons = [
      TextButton(
        onPressed: () => Navigator.pop(context),
        child: const Text("确定"),
      ),
    ];

    // 根据错误类型添加快捷操作按钮
    if (errorMessage.contains("请选择Flutter SDK路径")) {
      actionButtons.add(
        TextButton(
          onPressed: () {
            Navigator.pop(context);
            _selectFlutterSdkPath();
          },
          child: const Text("选择Flutter SDK"),
        ),
      );
    } else if (errorMessage.contains("输出目录不存在")) {
      actionButtons.add(
        TextButton(
          onPressed: () {
            Navigator.pop(context);
            _selectOutputDirectory();
          },
          child: const Text("选择输出目录"),
        ),
      );
    }

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("参数错误"),
        content: Text(errorMessage),
        actions: actionButtons,
      ),
    );
  }

  @override
  Widget createBody(
      {required BuildContext context, BoxConstraints? constraints}) {
    return ChangeNotifierProvider.value(
      value: _viewModel,
      child: Consumer<ScriptRunnerViewModel>(
        builder: (context, viewModel, _) {
          return SingleChildScrollView(
            padding: EdgeInsets.all(16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                InfoSection(
                  outputPath: viewModel.outputPath,
                  projectName: viewModel.projectName,
                  packageName: viewModel.packageName,
                  displayName: viewModel.displayName,
                  flutterSdkPath: viewModel.flutterSdkPath,
                  projectType: viewModel.projectType,
                  templateType: viewModel.templateType,
                  ideChoice: viewModel.ideChoice,
                  onOutputPathChanged: viewModel.updateOutputPath,
                  onProjectNameChanged: viewModel.updateProjectName,
                  onPackageNameChanged: viewModel.updatePackageName,
                  onDisplayNameChanged: viewModel.updateDisplayName,
                  onFlutterSdkPathChanged: viewModel.updateFlutterSdkPath,
                  onProjectTypeChanged: viewModel.updateProjectType,
                  onTemplateTypeChanged: viewModel.updateTemplateType,
                  onIdeChoiceChanged: viewModel.updateIdeChoice,
                  onSelectOutputDirectory: _selectOutputDirectory,
                  onSelectFlutterSdkPath: _selectFlutterSdkPath,
                ),
                SizedBox(height: 20.h),
                ActionButtons(
                  isRunning: viewModel.isRunning,
                  onRunPressed: _runScript,
                  onStopPressed: _stopScript,
                ),
                SizedBox(height: 20.h),
                OutputSection(
                  isRunning: viewModel.isRunning,
                  output: viewModel.commandOutput,
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    _viewModel.dispose();
    super.dispose();
  }
}
